package com.demo.explore.config;

import com.demo.explore.filter.ValidateCodeFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;


/**
 * 登录相关配置
 *
 * @author Logan
 *
 */
@Configuration
public class LoginConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private PersistentTokenRepository tokenRepository;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private ValidateCodeFilter validateCodeFilter;

    @Autowired
    private SmsCodeSecurityConfig smsCodeSecurityConfig;

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.apply(smsCodeSecurityConfig)

                // 设置验证码过滤器到过滤器链中，在UsernamePasswordAuthenticationFilter之前执行
                .and().addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class)

                // 设置自定义表单登录页面
                .formLogin().loginPage("/login.html")

                // 设置登录验证请求地址为自定义登录页配置action （"/login/form"）
                .loginProcessingUrl("/login/form")

                // 设置默认登录成功跳转页面
                .defaultSuccessUrl("/main.html")

                /* 授权请求设置 */
                .and().authorizeRequests()

                // 设置不需要授权的请求
                .antMatchers("/js/*", "/code/*", "/login.html").permitAll()

                // 其它任何请求都需要验证权限
                .anyRequest().authenticated()

                /* 记住我功能设置 */
                .and().rememberMe().tokenRepository(tokenRepository)

                // 【记住我功能】有效期为两周
                .tokenValiditySeconds(3600 * 24 * 14)

                // 设置UserDetailsService
                .userDetailsService(userDetailsService)

                // 暂时停用csrf，否则会影响验证
                .and().csrf().disable();
    }

}
